<template>
  <div class="max-w-4xl mx-auto space-y-8">
    <!-- Profile Header -->
    <Card>
      <CardHeader>
        <div class="flex items-center justify-between">
          <CardTitle class="flex items-center gap-2">
            <User class="w-5 h-5" />
            {{ t('profilePage.profileTitle') }}
          </CardTitle>
          <div v-if="!isEditing">
            <Button variant="outline" size="sm" @click="isEditing = true">
              <Edit3 class="w-4 h-4 mr-2" />
              {{ t('profilePage.edit') }}
            </Button>
          </div>
          <div v-else class="flex gap-2">
            <Button variant="outline" size="sm" @click="handleCancel">
              <X class="w-4 h-4 mr-2" />
              {{ t('profilePage.cancel') }}
            </Button>
            <Button size="sm" @click="handleSave">
              <Save class="w-4 h-4 mr-2" />
              {{ t('profilePage.save') }}
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div class="flex items-start gap-6">
          <Avatar class="w-24 h-24">
            <AvatarFallback class="text-2xl">
              {{ userProfile.name.charAt(0).toUpperCase() }}
            </AvatarFallback>
          </Avatar>

          <div class="flex-1 space-y-4">
            <div v-if="!isEditing">
              <h2 class="text-2xl font-bold">{{ userProfile.name }}</h2>
              <p v-if="userProfile.age" class="text-muted-foreground">
                {{ userProfile.age }} {{ t('profilePage.yearsOld') }}
              </p>
            </div>
            <div v-else class="space-y-4 max-w-md">
              <div class="space-y-2">
                <Label for="name">{{ t('profilePage.name') }}</Label>
                <Input id="name" v-model="editForm.name" />
              </div>
              <div class="space-y-2">
                <Label for="age">{{ t('profilePage.ageOptional') }}</Label>
                <Input id="age" type="number" v-model="editForm.age" />
              </div>
            </div>

            <div class="flex items-center gap-4">
              <Badge variant="secondary" class="flex items-center gap-1">
                <Trophy class="w-3 h-3" />
                {{ t('profilePage.level') }} {{ userProfile.level }}
              </Badge>
              <Badge variant="outline" class="flex items-center gap-1">
                <Calendar class="w-3 h-3" />
                {{ t('profilePage.joinedOn') }}
                {{ new Date(userProfile.joinDate).toLocaleDateString("zh-CN") }}
              </Badge>
            </div>

            <div class="space-y-2">
              <div class="flex justify-between text-sm">
                <span>{{ t('profilePage.levelUpProgress') }}</span>
                <span
                  >{{ userProfile.totalTests }}/{{
                    userProfile.level * 3
                  }}
                  {{ t('profilePage.tests') }}</span
                >
              </div>
              <Progress :model-value="progressToNextLevel" class="h-2" />
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- Left Column - Stats -->
      <div class="lg:col-span-2 space-y-6">
        <!-- Performance Overview -->
        <Card v-if="performanceStats">
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <BarChart3 class="w-5 h-5" />
              {{ t('profilePage.performanceOverview') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div
                class="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg"
              >
                <div class="text-2xl font-bold text-blue-600">
                  {{ performanceStats.totalTests }}
                </div>
                <div class="text-sm text-muted-foreground">{{ t('profilePage.totalTests') }}</div>
              </div>
              <div
                class="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg"
              >
                <div class="text-2xl font-bold text-green-600">
                  {{ performanceStats.bestScore }}
                </div>
                <div class="text-sm text-muted-foreground">{{ t('profilePage.highestScore') }}</div>
              </div>
              <div
                class="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg"
              >
                <div class="text-2xl font-bold text-purple-600">
                  {{ performanceStats.recentAverage }}
                </div>
                <div class="text-sm text-muted-foreground">{{ t('profilePage.recentAverage') }}</div>
              </div>
              <div
                class="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg"
              >
                <div class="text-2xl font-bold text-orange-600">
                  {{ performanceStats.uniqueTests }}
                </div>
                <div class="text-sm text-muted-foreground">{{ t('profilePage.testTypes') }}</div>
              </div>
            </div>

            <div
              v-if="performanceStats.bestTestType"
              class="mt-4 p-3 bg-muted rounded-lg"
            >
              <div class="flex items-center gap-2">
                <Target class="w-4 h-4 text-primary" />
                <i18n-t keypath="profilePage.bestAt" tag="span" class="text-sm">
                  <template #testType>
                    <strong>{{ performanceStats.bestTestType }}</strong>
                  </template>
                </i18n-t>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- Test History -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <TrendingUp class="w-5 h-5" />
              {{ t('profilePage.testHistory') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div v-if="testHistory.length > 0" class="space-y-3">
              <div
                v-for="(result, index) in testHistory"
                :key="index"
                class="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors"
              >
                <div class="flex-1">
                  <h4 class="font-medium">{{ result.testType }}</h4>
                  <p class="text-sm text-muted-foreground">
                    {{
                      new Date(result.timestamp).toLocaleDateString("zh-CN", {
                        year: "numeric",
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      })
                    }}
                  </p>
                  <p class="text-xs text-muted-foreground mt-1">
                    {{ result.details }}
                  </p>
                </div>
                <div class="text-right">
                  <div class="text-xl font-bold text-primary">
                    {{ result.score }}
                  </div>
                  <div
                    v-if="result.percentile"
                    class="text-xs text-muted-foreground"
                  >
                    {{ t('profilePage.percentile', { percentile: Math.round(result.percentile) }) }}
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-8 text-muted-foreground">
              <BarChart3 class="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>{{ t('profilePage.noTestHistory') }}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- Right Column -->
      <div class="space-y-6">
        <!-- Recent Achievements -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Award class="w-5 h-5" />
              {{ t('profilePage.achievementsShowcase') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div v-if="recentAchievements.length > 0" class="space-y-3">
              <div
                v-for="achievement in recentAchievements"
                :key="achievement.id"
                class="flex items-center gap-3 p-3 bg-yellow-50 dark:bg-yellow-950 rounded-lg"
              >
                <component
                  :is="achievement.icon"
                  class="w-6 h-6 text-yellow-500"
                />
                <div class="flex-1">
                  <h4 class="font-medium">{{ achievement.name }}</h4>
                  <p class="text-sm text-muted-foreground">
                    {{ achievement.description }}
                  </p>
                  <p
                    v-if="achievement.unlockedDate"
                    class="text-xs text-muted-foreground mt-1"
                  >
                    {{
                      new Date(achievement.unlockedDate).toLocaleDateString(
                        "zh-CN"
                      )
                    }}
                  </p>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-6 text-muted-foreground">
              <Trophy class="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p className="text-sm">{{ t('profilePage.unlockAchievementsPrompt') }}</p>
            </div>
          </CardContent>
        </Card>

        <!-- User Statistics Summary -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Brain class="w-5 h-5" />
              {{ t('profilePage.personalStats') }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-4">
            <div class="grid grid-cols-2 gap-3 text-center">
              <div class="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div class="text-lg font-bold text-blue-600">
                  {{ userProfile.level }}
                </div>
                <div class="text-xs text-muted-foreground">{{ t('profilePage.currentLevel') }}</div>
              </div>
              <div class="p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                <div class="text-lg font-bold text-green-600">
                  {{ userProfile.averageScore }}
                </div>
                <div class="text-xs text-muted-foreground">{{ t('profilePage.averageScore') }}</div>
              </div>
              <div class="p-3 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div class="text-lg font-bold text-purple-600">
                  {{ userProfile.totalTests }}
                </div>
                <div class="text-xs text-muted-foreground">{{ t('profilePage.totalTests') }}</div>
              </div>
              <div class="p-3 bg-orange-50 dark:bg-orange-950 rounded-lg">
                <div class="text-lg font-bold text-orange-600">
                  {{ recentAchievements.length }}
                </div>
                <div class="text-xs text-muted-foreground">{{ t('profilePage.unlockedAchievements') }}</div>
              </div>
            </div>

            <div class="p-3 bg-muted rounded-lg">
              <div class="text-sm text-muted-foreground mb-1">
                {{ t('profilePage.joined') }}
                {{
                  Math.floor(
                    (Date.now() - new Date(userProfile.joinDate).getTime()) /
                      (1000 * 60 * 60 * 24)
                  )
                }}
                {{ t('profilePage.daysAgo') }}
              </div>
              <div class="text-sm text-muted-foreground">
                {{ t('profilePage.nextLevelNeeds') }}
                {{
                  Math.max(0, userProfile.level * 3 - userProfile.totalTests)
                }}
                {{ t('profilePage.testsNeeded') }}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
import {
  User,
  Calendar,
  Trophy,
  Edit3,
  Save,
  X,
  TrendingUp,
  Target,
  Brain,
  Award,
  BarChart3,
} from "lucide-vue-next";

const { t } = useI18n();

const props = defineProps({
  userProfile: { type: Object, required: true },
  testResults: { type: Array, default: () => [] },
  achievements: { type: Array, default: () => [] },
});

const emit = defineEmits(["updateProfile"]);

const isEditing = ref(false);
const editForm = reactive({
  name: props.userProfile.name,
  age: props.userProfile.age?.toString() || "",
});

// Watch for external changes to the profile and update the form
watch(
  () => props.userProfile,
  (newProfile) => {
    editForm.name = newProfile.name;
    editForm.age = newProfile.age?.toString() || "";
  },
  { deep: true }
);

const handleSave = () => {
  emit("updateProfile", {
    ...props.userProfile,
    name: editForm.name,
    age: editForm.age ? parseInt(editForm.age, 10) : undefined,
  });
  isEditing.value = false;
};

const handleCancel = () => {
  editForm.name = props.userProfile.name;
  editForm.age = props.userProfile.age?.toString() || "";
  isEditing.value = false;
};

const testHistory = computed(() => {
  return [...props.testResults]
    .sort(
      (a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    )
    .slice(0, 10);
});

const performanceStats = computed(() => {
  if (props.testResults.length === 0) return null;

  const scores = props.testResults.map((r) => r.score);
  const bestScore = Math.max(...scores);
  const recentScores = [...props.testResults].slice(-5).map((r) => r.score);
  const recentAverage =
    recentScores.reduce((sum, score) => sum + score, 0) / recentScores.length;

  const testsByType = props.testResults.reduce((acc, result) => {
    if (!acc[result.testType]) {
      acc[result.testType] = [];
    }
    acc[result.testType].push(result.score);
    return acc;
  }, {});

  const bestTestType = Object.entries(testsByType).reduce(
    (best, [testType, scores]) => {
      const avg = scores.reduce((sum, score) => sum + score, 0) / scores.length;
      return avg > best.average ? { testType, average: avg } : best;
    },
    { testType: "", average: 0 }
  );

  return {
    bestScore,
    recentAverage: Math.round(recentAverage),
    bestTestType: bestTestType.testType,
    totalTests: props.testResults.length,
    uniqueTests: Object.keys(testsByType).length,
  };
});

const progressToNextLevel = computed(() => {
  const testsForNextLevel = props.userProfile.level * 3;
  const progress = (props.userProfile.totalTests / testsForNextLevel) * 100;
  return Math.min(100, progress);
});

const recentAchievements = computed(() => {
  return [...props.achievements]
    .filter((a) => a.unlocked)
    .sort(
      (a, b) =>
        (new Date(b.unlockedDate)?.getTime() || 0) -
        (new Date(a.unlockedDate)?.getTime() || 0)
    )
    .slice(0, 6);
});
</script>
